import React from "react"
import {connect} from 'react-redux'
import {Row, Col, Button, Modal, ModalHeader, ModalBody, ModalFooter, Label} from "reactstrap"
import {AvForm, AvInput, AvGroup, AvFeedback, AvField} from "availity-reactstrap-validation"
import Flatpickr from "react-flatpickr"
import {Russian} from 'flatpickr/dist/l10n/ru.js'

import {EVENTS_MODAL_STATUS, EVENT_MODAL_FIELD, CLEAR_EVENTS_MODAL} from '../../../redux/constants/events'
import {getEventsTypes, addEvent} from '../../../redux/actions/events'
import {setEventModalLocations} from '../../../redux/actions/events'
import {setData, setFieldData} from '../../../redux/actions/helper'
import SelectProject from '../../general/SelectProject'
import Organization from '../../../components/general/YandexAPI/Organization'
import FullLoadingSpinner from "../../@vuexy/spinner/Full-loading-spinner";
import "flatpickr/dist/flatpickr.min.css";
import "../../../assets/scss/plugins/forms/flatpickr/flatpickr.scss"
import "../../../assets/scss/components/reactstrap/modal/project-modal.scss"
import "../../../assets/scss/components/reactstrap/modal/events-modal.scss"

class EventsModal extends React.Component {

  constructor(props) {
    super(props);
    this.toggleModal = this.toggleModal.bind(this)

    this.state = {
      selectProjectInvalid: false,
      organizationInvalid: false,
      dateStartInvalid: false,
      dateEndInvalid: false,
      timeStartInvalid: false,
      timeEndInvalid: false,
      selectedProject: false,
    }
  }

  handleValidSubmitEvent = () => {
    if (!Object.values(this.state).includes(true)) {
      this.props.addEvent(this.props.locationsData, this.props.modalData, this.props.userFilterData)
    }
  }

  toggleModal = () => {
    this.props.setData(EVENTS_MODAL_STATUS, false)
    this.props.setData(CLEAR_EVENTS_MODAL)
    this.setState({
      selectProjectInvalid: false,
      organizationInvalid: false,
      dateStartInvalid: false,
      dateEndInvalid: false,
      timeStartInvalid: false,
      timeEndInvalid: false,
    })
  }

  customValidation = () => {
    !this.props.modalData.project_id && this.setState({selectProjectInvalid: true})
    !this.props.locationsData && this.setState({organizationInvalid: true})
    !this.props.modalData.dateStart && this.setState({dateStartInvalid: true})
    !this.props.modalData.dateEnd && this.setState({dateEndInvalid: true})
    !this.props.modalData.timeStart && this.setState({timeStartInvalid: true})
    !this.props.modalData.timeStart && this.setState({timeEndInvalid: true})
  }

  selectProjectOnChange = (e) => {
    if (e.value) {
      this.setState({selectProjectInvalid: false})
      this.props.setFieldData(EVENT_MODAL_FIELD, "project_id", e.value)
    }
  }

  organizationOnClick = (e) => {
    if (e && this.state.organizationInvalid) {
      this.setState({organizationInvalid: false})
    }
    this.props.setEventModalLocations(e)
  }

  render() {
    const dateStart = this.props.modalData.dateStart
    const dateEnd = this.props.modalData.dateEnd

    return (
      <React.Fragment>
        <Modal
          isOpen={this.props.modal}
          toggle={this.toggleModal}
          size="lg"
        >
          <ModalHeader toggle={this.toggleModal}>Добавить событие</ModalHeader>

          <AvForm onValidSubmit={this.handleValidSubmitEvent} className="authentication-form mt-1" id="addEventForm">
            {this.props.spinner.indexOf('event-create') !== -1 && <FullLoadingSpinner/>}
            <ModalBody>
              <Row>
                <Col md="5">
                  <div>
                    <AvGroup className={'event-form-item'}>
                      <Label for="projectList">Проект</Label>
                      <SelectProject
                        maxMenuHeight={220}
                        projectList={this.props.projectsList}
                        setData={this.props.setData}
                        onChange={e => this.selectProjectOnChange(e)}
                        required={this.state.selectProjectInvalid}
                        owner={this.props.verify_id}
                        isGetProjects={true}
                        onlyOwners
                      />
                    </AvGroup>
                  </div>
                  <div>
                    <AvGroup className={'event-form-item'}>
                      <Label for="nameEvent">Название</Label>
                      <AvInput
                        className="popup-modal-input"
                        autoComplete="off"
                        type="text"
                        name="nameEvent"
                        id="nameEvent"
                        placeholder="Название"
                        value={this.props.modalData.name}
                        onChange={(e) => this.props.setFieldData(EVENT_MODAL_FIELD, "name", e.target.value)}
                        required
                      />
                      <AvFeedback>Введите название</AvFeedback>
                    </AvGroup>
                  </div>
                  <div>
                    <AvGroup className={'event-form-item'}>
                      <Label for="typeEvent">Тип события</Label>
                      <AvField
                        className={`${!this.props.modalData.type_id ? 'event-modal-select' : ""}`}
                        type="select"
                        name="typeEvent"
                        id="typeEvent"
                        validate={{required: {value: true, errorMessage: 'Выберите тип события'}}}
                        onChange={e => this.props.setFieldData(EVENT_MODAL_FIELD, "type_id", e.target.value)}
                      >
                        <option className="select-placeholder" value="" disabled hidden>Выберите тип</option>
                        {this.props.eventsTypes && this.props.eventsTypes.map(item => <option value={item.id} key={item.id}>{item.name}</option>)}
                      </AvField>
                    </AvGroup>
                  </div>
                </Col>
                <Col md="7">
                  <div>
                    <AvGroup className={'event-form-item'}>
                      <Label for="positionEvent">Место</Label>
                      <Organization
                        id='organizationEventEdit'
                        className='popup-modal-input form-control'
                        placeholder='Место'
                        onClick={this.organizationOnClick}
                        required={this.state.organizationInvalid}
                      />
                    </AvGroup>
                  </div>
                  <Row>
                    <Col md={6}>
                      <AvGroup className={'event-form-item'}>
                        <Label for="dateStartEvent">Дата начала</Label>
                        <Flatpickr
                          options={{
                            dateFormat: "d-m-Y",
                            minDate: "today",
                            locale: Russian,
                            maxDate: dateEnd ? new Date(dateEnd[0], dateEnd[1], dateEnd[2]) : ''
                          }}
                          onChange={e => {
                            this.props.setFieldData(EVENT_MODAL_FIELD, "dateStart", [e[0].getFullYear(), e[0].getMonth(), e[0].getDate()])
                            this.state.dateStartInvalid && this.setState({dateStartInvalid: false})
                          }}
                          className={`form-control popup-modal-input ${this.state.dateStartInvalid ? 'is-invalid input-invalid' : ''}`}
                          name="dateStartEvent"
                          id="dateStartEvent"
                          placeholder="01-01-2020"
                        />
                        <div className="invalid-feedback">Выберите дату начала</div>
                      </AvGroup>
                    </Col>
                    <Col md={6}>
                      <AvGroup className={'event-form-item'}>
                        <Label for="timeStartEvent">Время начала</Label>
                        <Flatpickr
                          options={{
                            enableTime: true,
                            noCalendar: true,
                            dateFormat: "H:i",
                            time_24hr: true,
                          }}
                          onChange={e => {
                            this.props.setFieldData(EVENT_MODAL_FIELD, "timeStart", [e[0].getHours(), e[0].getMinutes(), 0])
                            this.state.timeStartInvalid && this.setState({timeStartInvalid: false})
                          }}
                          className={`form-control popup-modal-input ${this.state.timeStartInvalid ? 'is-invalid input-invalid' : ''}`}
                          name="timeStartEvent"
                          id="timeStartEvent"
                          placeholder="08:00"
                        />
                        <div className="invalid-feedback">Выберите время начала</div>
                      </AvGroup>
                    </Col>
                  </Row>
                  <Row>
                    <Col md="6">
                      <AvGroup className={'event-form-item'}>
                        <Label for="dateEndEvent">Дата окончания</Label>
                        <Flatpickr
                          options={{
                            dateFormat: "d-m-Y",
                            locale: Russian,
                            minDate: dateStart ? new Date(dateStart[0], dateStart[1], dateStart[2]) : 'today'
                          }}
                          onChange={e => {
                            this.props.setFieldData(EVENT_MODAL_FIELD, "dateEnd", [e[0].getFullYear(), e[0].getMonth(), e[0].getDate()])
                            this.state.dateEndInvalid && this.setState({dateEndInvalid: false})
                          }}
                          className={`form-control popup-modal-input ${this.state.dateEndInvalid ? 'is-invalid input-invalid' : ''}`}
                          name="dateEndEvent"
                          id="dateEndEvent"
                          placeholder="30-12-2020"
                        />
                        <div className="invalid-feedback">Выберите дату окончания</div>
                      </AvGroup>
                    </Col>
                    <Col md="6">
                      <AvGroup className={'event-form-item'}>
                        <Label for="timeEndEvent">Время окончания</Label>
                        <Flatpickr
                          options={{
                            enableTime: true,
                            noCalendar: true,
                            dateFormat: "H:i",
                            time_24hr: true,
                          }}
                          onChange={e => {
                            this.props.setFieldData(EVENT_MODAL_FIELD, "timeEnd", [e[0].getHours(), e[0].getMinutes(), 0])
                            this.state.timeEndInvalid && this.setState({timeEndInvalid: false})
                          }}
                          className={`form-control popup-modal-input ${this.state.timeEndInvalid ? 'is-invalid input-invalid' : ''}`}
                          name="timeEndEvent"
                          id="timeEndEvent"
                          placeholder="12:00"
                        />
                        <div className="invalid-feedback">Выберите время окончания</div>
                      </AvGroup>
                    </Col>
                  </Row>
                </Col>
              </Row>
            </ModalBody>
            <ModalFooter>
              <Button.Ripple
                color="primary"
                type="submit"
                className="project-modal-button"
                onClick={this.customValidation}
              >
                Сохранить
              </Button.Ripple>
            </ModalFooter>
          </AvForm>
        </Modal>
      </React.Fragment>
    )
  }
}

const mapStateToProps = state => {
  return {
    modal: state.events.modal,
    modalData: state.events.modalData,
    userFilterData: state.events.userFilterData,
    locationsData: state.events.locationsData,
    eventsTypes: state.events.eventsTypes.data,
    spinner: state.helper.spinner,
    projectsList: state.projects.ownerProjectList,
    verify_id: state.users.data.verify_id,
  }
}

export default connect(mapStateToProps, {
  setData,
  setEventModalLocations,
  setFieldData,
  getEventsTypes,
  addEvent
})(EventsModal)
